/*
 * testThread.h
 *
 *  Created on: 2013. 3. 18.
 *      Author: jaty
 */

#ifndef TESTTHREAD_H_
#define TESTTHREAD_H_

#include "prmMQlib.h"
#include "myMacros.h"
#include "runnable.h"
#include "protobufWrapper.h"

class testThread : public runnable {
private:
	class testMqConsumer : public prmMQlib::ConsumerClient
	{
	public:
		testMqConsumer() {};

	  void OnMessage(int mesgType, char* mesg, int length) const {
		  cout << "Received Msg: " << mesg << endl;
	  }

	  virtual void transportInterrupted() {}
	  virtual void transportResumed(){}
	  virtual void onException( const CMSException& ex){}

	protected:
	};
	bool isRunning;
	pthread_t testThr;
	testMqConsumer* consumer;
	prmMQlib::CPrmMQlib *pMq;
	prmMQlib::CPrmMQlib *cMq;
	string qName;


public:
	testThread(prmMQlib::CPrmMQlib *pMq, string brokeruri, string qName) {
		this->pMq = pMq;
		this->qName = qName;

		pMq->addProducer("testMqQueueTrade", true, false);

		exServer::Instrument tmpInst;
		exServer::Instrument tmpTrade;

		//cMq = new prmMQlib::CPrmMQlib;
		//consumer = new testMqConsumer();

		//cMq->initPrmMQlib(brokeruri, "testMqConsumer");
		//int retCode = (int) cMq->addConsumer(consumer,qName,true,true);
		//cout << "addConsumer RetCode=" << retCode << endl;
		pthread_create(&testThr, NULL, &runnable::run_thread, (void*)this);
	}
	~testThread() {
		//delete consumer;
		//delete cMq;
		int status=0;
		pthread_join(testThr, (void**)&status);
	}
	testMqConsumer* getConsumerPointer() {
		return consumer;
	}
	void stopRunning() {
		isRunning = false;
	}
	void run() {
/*		double bid = 230.5;
		stringstream ss;

		isRunning=true;
		while(isRunning) {
			ss.str("");
			ss << bid;
			string tmpStr = ss.str();
			cout << "Sending string=[" << tmpStr << "]" << endl;
			pMq->sendTextMessage(qName, tmpStr);
			bid += 0.5;
			sleep(3);
		}
*/
		Instrument inst(250, 10, 20.0);
		Trade trade(250, 10, 20.0);
		int protoInstByteSize = inst.getProtoInstByteSize();
		int protoTradeByteSize = trade.getProtoTradeByteSize();
		unsigned char instBuf[protoInstByteSize], tradeBuf[protoTradeByteSize];

		while(isRunning) {
			//string msgStr = inst.getInstMsgString();
			inst.getInstMsgByteArray(instBuf);
			cout << "[Sending Instrument]" << endl;
			inst.printTestInst();
			pMq->sendBytesMessage(qName, instBuf, protoInstByteSize);
			sleep(2);
			inst.reGenerateRandomInst();

			//string trdStr = trade.getTradeMsgString();
			trade.getTradeMsgByteArray(tradeBuf);
			cout << "[Sending Trade]" << endl;
			trade.printTestTrade();
			pMq->sendBytesMessage("testMqQueueTrade", tradeBuf, protoTradeByteSize);
			sleep(2);
			trade.reGenerateTestTrade();
		}
	}
};


#endif /* TESTTHREAD_H_ */
